package com.cade.agriculturemall.view.personalCenter.manageAddress;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.base.BaseViewHolder;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.model.UserInfoEntity;
import com.cade.agriculturemall.view.personalCenter.editAddress.EditAddressActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lobby on 2017/12/22.
 */

public class ManageAddressAdapter extends BaseAdapter implements View.OnClickListener {
    private List<AddressEntity> mEntityList = new ArrayList<>();
    private Context mContext;
    private AddressEntity entity;

    public ManageAddressAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public void onBindViewHolderWrapper(final BaseViewHolder holder, final int position) {
        TextView tvName = holder.findViewById(R.id.item_address_name);
        TextView tvPhone = holder.findViewById(R.id.item_address_phone);
        TextView tvAddress = holder.findViewById(R.id.item_address_detail);
        final CheckBox checkBox = holder.findViewById(R.id.item_address_checkbox);
        TextView tvEdit = holder.findViewById(R.id.item_address_tv_edit);
        TextView tvDelete = holder.findViewById(R.id.item_address_tv_delete);
        RelativeLayout relativeLayout = holder.findViewById(R.id.item_address_rl);
        checkBox.setTag(position);
        tvDelete.setTag(position);
        tvEdit.setTag(position);

        if (position == 0) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0, 0, 0, 10);//4个参数按顺序分别是左上右下
            relativeLayout.setLayoutParams(layoutParams);
        }
        if (mEntityList != null) {
            entity = mEntityList.get(position);
            if (entity != null) {
                tvName.setText(entity.getContractor());
                tvPhone.setText(entity.getMobile());
                checkBox.setText("设为默认");
                if (entity.getIsfirst().equals("1")) {
                    checkBox.setChecked(true);
                    checkBox.setTextColor(Color.RED);
                } else {
                    checkBox.setChecked(false);
                    checkBox.setTextColor(Color.BLACK);
                }
                String address = "";
                String procincecity = entity.getProvince() + entity.getCity();
                if (entity.getCounty() != null) {
                    address += procincecity + entity.getCounty() + entity.getStress() + entity.getAddress();
                } else {
                    address += procincecity + entity.getStress() + entity.getAddress();
                }

                tvAddress.setText(address);
                tvEdit.setOnClickListener(this);
            }
        }
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                if (((CheckBox) v).isChecked()) {
                    for (AddressEntity addressEntity : mEntityList) {
                        addressEntity.setIsfirst("2");
                        checkBox.setChecked(true);
                    }

                    mEntityList.get(p).setIsfirst("1");
                    checkBox.setTextColor(Color.RED);
                } else {
//                    entity.setIsfirst("2");
//                    checkBox.setChecked(false);
//                    checkBox.setTextColor(Color.BLACK);
//                    mEntityList.get(p).setIsfirst("2");
                }
                doModityIsFirst(mEntityList);
                AddressEntity addressEntity = mEntityList.get(p);
//                mEntityList.remove(p);
//                mEntityList.add(0, addressEntity);
//                notifyItemMoved(p, 0);
                notifyDataSetChanged();
            }
        });
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int section = (int) v.getTag();
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
                builder.setMessage("确认要删除改地址吗？");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteAddress(section);
                    }
                });
                android.app.AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new BaseViewHolder(parent, R.layout.item_my_address);
    }


    @Override
    public int getItemCount() {
        return mEntityList.size();
    }

    public void setEntityList(List<AddressEntity> EntityList) {
        if (EntityList != null)
            this.mEntityList = EntityList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_address_tv_edit:
                final int positionEdit = (int) v.getTag();
                Intent intent = new Intent(mContext, EditAddressActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("AddressObjectId", mEntityList.get(positionEdit).getObjectId());
                mContext.startActivity(intent);
                break;
        }
    }

    public void deleteAddress(final int section) {
        AVQuery<AddressEntity> addressEntityAVQuery = new AVQuery<>("user_address");
        addressEntityAVQuery.whereEqualTo("objectId", mEntityList.get(section).getObjectId());
        addressEntityAVQuery.deleteAllInBackground(new DeleteCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    mEntityList.remove(section);
                    notifyDataSetChanged();
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    //             mEntityList 批量保存
    public void doModityIsFirst(final List<AddressEntity> entityList) {
//        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
//        UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
//        AVQuery<AddressEntity> addressEntityAVQuery = new AVQuery<>("user_address");
//        addressEntityAVQuery.whereEqualTo("ownerObjectId", user);
//        addressEntityAVQuery.findInBackground(new FindCallback<AddressEntity>() {
//            @Override
//            public void done(List<AddressEntity> list, AVException e) {
//                List<AddressEntity> todos = entityList;
//                try {
//                    AVObject.saveAll(todos);
//                } catch (AVException e1) {
//                    e1.printStackTrace();
//                }
//            }
//        });

        AVQuery<AddressEntity> addressEntityAVQuery = new AVQuery<>("user_address");
        addressEntityAVQuery.findInBackground(new FindCallback<AddressEntity>() {
            @Override
            public void done(List<AddressEntity> list, AVException e) {

                if (e == null) {
                    List<AddressEntity> todos = entityList;
                    AVObject.saveAllInBackground(todos, new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e == null) {
//                                Toast.makeText(mContext, "baoxunxhenggong", Toast.LENGTH_SHORT).show();
                            } else {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });

    }
}
